package com.insigma.business.qrcode.common.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.alibaba.xxpt.gateway.shared.client.http.ExecutableClient;
import com.alibaba.xxpt.gateway.shared.client.http.GetClient;
import com.alibaba.xxpt.gateway.shared.client.http.PostClient;
import com.google.common.collect.Maps;

import com.insigma.business.qrcode.common.dto.*;
import com.insigma.business.qrcode.common.entity.ZzdOrganizationDetailBO;
import com.insigma.business.qrcode.common.service.ZzdService;
import com.insigma.business.qrcode.common.util.BizCheckUtil;
import com.insigma.business.qrcode.common.util.ZzdFactory;
import com.insigma.business.qrcode.soldier.util.OkHttp3Util;
import com.insigma.business.qrcode.soldier.util.OssUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;


@Slf4j
@Service("zzdService")
public class ZzdServiceImpl implements ZzdService {

    @Value("${zzd.ak}")
    private String AK;
    @Value("${zzd.sk}")
    private String SK;
    @Value("${zzd.host}")
    private String URL;

    @Value("${zzd.prod.ak}")
    private String prodAk = "zhlb-EhkkC34UfgW60oP6sF3bY3M3u";
    @Value("${zzd.prod.sk}")
    private String prodSk = "9c5M4CqX1EcZ2LSRq525M67Cl2azQO24J4VRE124";
    @Value("${zzd.prod.host}")
    private String prodHost = "openplatform-pro.ding.zj.gov.cn";

    @Value("${zzd.prod.ak_2}")
    private String prodAk_2 = "zhlb-EhkkC34UfgW60oP6sF3bY3M3u";
    @Value("${zzd.prod.sk_2}")
    private String prodSk_2 = "9c5M4CqX1EcZ2LSRq525M67Cl2azQO24J4VRE124";
    @Value("${zzd.prod.host_2}")
    private String prodHost_2 = "openplatform-pro.ding.zj.gov.cn";

    @Value("${spring.profiles.active}")
    private String env;


    @Value("${zzd.prod.tenantId}")
    private String tenantId = "196729";

    @Value("${sm.tmp.dir}")
    private String tmpDir;

    private static String classification = "yida";

    private String appType = "APP_EKMLLDCQRGA7X6E8V87J";
    private String systemToken = "VSHCVF3U2XS0G10DZXX71V11R19HS2P0KQFGAK0";
    private String pubUserId = "yida_pub_account";


    private ExecutableClient prodExecutableClient;

    private static ExecutableClient executableClient;

    @PostConstruct
    public void init() {
        executableClient = ZzdFactory.getExecutableClient(AK,SK,URL);
        executableClient.setProtocal("https");
        executableClient.init();

    }

    private ExecutableClient getExecutableClient() {
        if (prodExecutableClient == null) {
            log.info("aksk: {},{},{}", prodAk, prodSk, prodHost);
            prodExecutableClient = ZzdFactory.getExecutableClient(prodAk, prodSk, prodHost);
        }

        return prodExecutableClient;
    }

    private ExecutableClient getExecutableClient_2() {
        if (prodExecutableClient == null) {
            log.info("aksk: {},{},{}", prodAk_2, prodSk_2, prodHost_2);
        //    prodExecutableClient = ZzdFactory.getExecutableClient(prodAk_2, prodSk_2, prodHost_2);
        }

        return prodExecutableClient;
    }


    @Override
    public Boolean sendSmsCode(String phoneNumber, String code) {
        String api = "/message/sendSms";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("pwd", code);
        PostClient postClient = executableClient.newPostClient(api);
        postClient.addParameter("phoneNumber", phoneNumber);
        postClient.addParameter("jsonContent", jsonObject.toString());
        postClient.addParameter("templateId", "sms_buc_5");
        String apiResult = postClient.post();

        Boolean rFlog = false;
        try {
            JSONObject result = JSONObject.parseObject(apiResult);
            rFlog = result.getBoolean("success");
        } catch (Exception e) {
            log.error("send sms error:{}", e);
        }
        return rFlog;
    }

    @Override
    public List<String> pageSubOrganizationCodes(String orgCode) {
        ExecutableClient executableClient = getExecutableClient();
        String api = "/mozi/organization/pageSubOrganizationCodes";
        PostClient postClient = executableClient.newPostClient(api);
        postClient.addParameter("tenantId", tenantId);
        postClient.addParameter("organizationCode", orgCode);
        String apiResult = postClient.post();
        log.info("result:{}", apiResult);
        return extractListResult(apiResult, String.class);
    }


    @Override
    public ZzdOrganizationDetailBO getOrganizationByCode(String orgCode) {
        ExecutableClient executableClient = getExecutableClient();
        String api = "/mozi/organization/getOrganizationByCode";
        PostClient postClient = executableClient.newPostClient(api);
        postClient.addParameter("tenantId", tenantId);
        postClient.addParameter("organizationCode", orgCode);
        String apiResult = postClient.post();
        log.info("result:{}", apiResult);
        return extractObjectResult(apiResult, ZzdOrganizationDetailBO.class);
    }

    @Override
    public List<String> pageOrganizationEmployeeCodes(String orgCode) {
        ExecutableClient executableClient = getExecutableClient();
        String api = "/mozi/organization/pageOrganizationEmployeeCodes";
        PostClient postClient = executableClient.newPostClient(api);
        postClient.addParameter("tenantId", tenantId);
        postClient.addParameter("organizationCode", orgCode);
        String apiResult = postClient.post();
        log.info("result:{}", apiResult);
        return extractListResult(apiResult, String.class);
    }

    @Override
    public ZzdEmployeeDetailBO getEmployeeByCode(String employeeCode) {
        ExecutableClient executableClient = getExecutableClient();
        String api = "/mozi/employee/getEmployeeByCode";
        PostClient postClient = executableClient.newPostClient(api);
        postClient.addParameter("tenantId", tenantId);
        postClient.addParameter("employeeCode", employeeCode);
        String apiResult = postClient.post();
        log.info("result:{}", apiResult);
        return extractObjectResult(apiResult, ZzdEmployeeDetailBO.class);
    }

    @Override
    public String getZzdAvatarByMobile(String mobile) {
        log.info("根据手机号获取头像，{}",mobile);
        ZzdAccountBO idNoByMobile = getIdNoByMobile(mobile);
        if (idNoByMobile != null) {
            ZzdEmployeeDetailBO employeeByCode = getEmployeeByCode(idNoByMobile.getEmployeeCode());
            if (employeeByCode != null && Strings.isNotBlank(employeeByCode.getGovEmpAvatar())) {
                String id = employeeByCode.getGovEmpAvatar().substring(1);
                String s = downloadImg(String.valueOf(idNoByMobile.getAccountId()), id);
                return s;
            }
        }
        return null;
    }


    public String downloadImg(String accountId, String path) {
        ExecutableClient executableClient = getExecutableClient();
        String api = "/media/download";
        GetClient getClient = executableClient.newGetClient(api);
        getClient.addParameter("access_token", getAccessToken().getAccessToken());
        getClient.addParameter("media_id", path);
        try {
            String objectKey = "avatar" + "/" + accountId + "/" + RandomStringUtils.randomAlphanumeric(18)  + ".png";

            CloseableHttpResponse b = getClient.getB();
            InputStream content = b.getEntity().getContent();
            String s = OssUtil.saveFile(content, objectKey);
            return s;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String addressBook() {
        ExecutableClient executableClient = getExecutableClient();
        String api = "/auth/scopesV2";
        PostClient postClient = executableClient.newPostClient(api);
        postClient.addParameter("tenantId", tenantId);
        String apiResult = postClient.post();
        log.info("result:{}", apiResult);
        return apiResult;
    }

    @Override
    public List<ZzdAccountBO> getAccountInfoByCode(String employeeCode) {
        ExecutableClient executableClient = getExecutableClient();
        String api = "/mozi/employee/listEmployeeAccountIds";
        PostClient postClient = executableClient.newPostClient(api);
        postClient.addParameter("tenantId", tenantId);
        postClient.addParameter("employeeCodes", employeeCode);
        String apiResult = postClient.post();
        log.info("result:{}", apiResult);
        return extractListResult(apiResult, ZzdAccountBO.class);
    }

    @Override
    public List<ZzdPositionDetailBO> listEmployeePositionsByEmployeeCode(String employeeCode) {
        ExecutableClient executableClient = getExecutableClient();
        String api = "/mozi/employee/listEmployeePositionsByEmployeeCode";
        PostClient postClient = executableClient.newPostClient(api);
        postClient.addParameter("tenantId", tenantId);
        postClient.addParameter("employeeCode", employeeCode);
        String apiResult = postClient.post();
        log.info("result:{}", apiResult);
        return extractListResult(apiResult, ZzdPositionDetailBO.class);
    }

    @Override
    public List<ZzdPositionDetailBO> listOrgEmployeePositionsByCodes(String orgCode, String employeeCode) {
        ExecutableClient executableClient = getExecutableClient();
        String api = "/mozi/employee/listOrgEmployeePositionsByCodes";
        PostClient postClient = executableClient.newPostClient(api);
        postClient.addParameter("tenantId", tenantId);
        postClient.addParameter("employeeCodes", employeeCode);
        postClient.addParameter("organizationCode", orgCode);
        String apiResult = postClient.post();
        log.info("result:{}", apiResult);
        return extractListResult(apiResult, ZzdPositionDetailBO.class);
    }


    private <T> T extractObjectResult(String apiResult, Class<T> clazz) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(apiResult);
            if (Boolean.TRUE.equals(jsonObject.getBoolean("success"))) {
                JSONObject content = jsonObject.getJSONObject("content");
                if (content != null) {
                    JSONObject data = content.getJSONObject("data");
                    if (data != null) {
                        return data.toJavaObject(clazz);
                    }
                }
            }
            return null;
        } catch (Exception e) {
            log.error("error:{}", e);
            return null;
        }
    }

    private <T> List<T> extractListResult(String apiResult, Class<T> clazz) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(apiResult);
            if (Boolean.TRUE.equals(jsonObject.getBoolean("success"))) {
                JSONObject content = jsonObject.getJSONObject("content");
                if (content != null) {
                    JSONArray data = content.getJSONArray("data");
                    if (data != null) {
                        return data.toJavaList(clazz);
                    }
                }
            }
            return new ArrayList<>();
        } catch (Exception e) {
            log.error("error:{}", e);
            return extractListResult(apiResult, clazz);
        }
    }

    public void test() {
        ExecutableClient executableClient = getExecutableClient();
        String api = "/auth/scopesV2";
        PostClient postClient = executableClient.newPostClient(api);
        postClient.addParameter("tenantId", tenantId);
        String apiResult = postClient.post();
        log.info("result:{}", apiResult);
    }

    @Override
    public String sendNotice(String receiverIds, String msg) {
        ExecutableClient executableClient = getExecutableClient();
        String api = "/message/workNotification";

        String mt = "{\"msgtype\":\"text\",\"text\":{\"content\":\"%s\"}} ";

        PostClient postClient = executableClient.newPostClient(api);

        postClient.addParameter("organizationCodes", "");
        postClient.addParameter("receiverIds", receiverIds);
        postClient.addParameter("tenantId", tenantId);
        postClient.addParameter("msg", String.format(mt, msg));

        String apiResult = postClient.post();
        log.info(apiResult);
        return apiResult;
    }

























    @Override
    public String sendNoticeOfNews(String receiverIds, String msg) {
        log.info("下发news：{}, {}", receiverIds, msg);
        ExecutableClient executableClient = getExecutableClient();
        String api = "/message/workNotification";


        String mt = msg;
        PostClient postClient = executableClient.newPostClient(api);

        postClient.addParameter("organizationCodes", "");
        postClient.addParameter("receiverIds", receiverIds);
        postClient.addParameter("tenantId", tenantId);
        postClient.addParameter("msg", String.format(mt, msg));

        String apiResult = postClient.post();
        log.info(apiResult);
        return apiResult;
    }

    @Override
    public YiDaResponse yidaFwzList(Integer pageNo, Integer pageSize) {
        log.info("yida 服务站列表,{},{}", pageNo, pageSize);
        String apiResult = queryYiDaResponse("FORM-VSHCV0BW2Q8TGAP8M59U3AAO3O9IU3NJ67BRBK9", pageNo, pageSize);
        log.info("result:{}", apiResult);
        if (Strings.isBlank(apiResult)) {
            return null;
        }
        return JSON.parseObject(apiResult, YiDaResponse.class);
    }

    @Override
    public YiDaResponse yidaWorkerList(Integer pageNo, Integer pageSize) {
        log.info("yida 人员列表,{},{}", pageNo, pageSize);
        String apiResult = queryYiDaResponse("FORM-VSHCVART2ZS0GB4HYVNEEKIVPXRFO1VW2TFGAK0", pageNo, pageSize);

        log.info("result:{}", apiResult);
        if (Strings.isBlank(apiResult)) {
            return null;
        }
        return JSON.parseObject(apiResult, YiDaResponse.class);
    }






























    @Override
    public ZzdAccountBO getIdNoByMobile(String mobile) {
        log.info("查询人员信息：{}", mobile);
        ExecutableClient executableClient = getExecutableClient();
        String api = "/mozi/employee/get_by_mobile";
        PostClient postClient = executableClient.newPostClient(api);
        postClient.addParameter("tenantId", tenantId);
        postClient.addParameter("areaCode", "86");
        postClient.addParameter("namespace", "local");
        postClient.addParameter("mobile", mobile);
        String apiResult = postClient.post();
        log.info("result:{}", apiResult);
        return extractObjectResult(apiResult, ZzdAccountBO.class);
    }






























    public String test(String receiverIds, String msg) {
        ExecutableClient executableClient = getExecutableClient();
        String api = "/message/workNotification";

        PostClient postClient = executableClient.newPostClient(api);

        postClient.addParameter("organizationCodes", "");
        postClient.addParameter("receiverIds", receiverIds);
        postClient.addParameter("tenantId", tenantId);
        postClient.addParameter("msg", msg);

        String apiResult = postClient.post();
        log.info(apiResult);
        return apiResult;
    }

    @Override
    public String getFreeRegistrationImg(String originUrl) {

        String api = "/yida/file/getOpenUrl.json";

        ExecutableClient executableClient = getExecutableClient();
        PostClient postClient = executableClient.newPostClient(api);
        postClient.addParameter("appType", appType);
        postClient.addParameter("systemToken", systemToken);
        postClient.addParameter("userId", pubUserId);
        postClient.addParameter("timeout", "864000000");
        postClient.addParameter("fileUrl", originUrl);
        String apiResult = postClient.post();

        log.info("result:{}", apiResult);
        if (Strings.isBlank(apiResult)) {
            return "";
        }
        JSONObject object = JSONObject.parseObject(apiResult);
        return object.getString("result");
    }

    @Override
    public String convertYdImgToMy(String idCardNo, String originUrl) {
        String yidaUrl = getFreeRegistrationImg(originUrl);

        if ("dev".equals(env)) {
            yidaUrl = yidaUrl.replace("http://oss-cn-hangzhou-zjzwy01-d01-a.cloud.zj.gov.cn", "http://172.18.103.246:46911");
        }
        String s = OssUtil.uploadFileToOss(yidaUrl, idCardNo, classification, tmpDir);
        return s;
    }

    private void aaaa() {
        String apiResult = queryYiDaResponse("FORM-GWLBV8TU25QIO4PI5XCL0ANQ3LR7Q1YS9HDKMKL4", 1, 20);
        log.info("result:{}", apiResult);
    }

    private static void addPositionToYida() {
        JSONObject request = new JSONObject();
        request.put("pageNo", 1);
        request.put("pageSize", 100);
        request.put("published", true);

        JSONObject object = new JSONObject();
        object.put("operation", "8101.all.ss.job.recruit.position.company.search");
        object.put("partnerId", "6666111202");
        object.put("source", "PC");
        object.put("timestamp", "1585482678193");
        object.put("bizReqData", JSONObject.toJSONString(request));
        String s = object.toString();
        Map<String, String> map = Maps.newHashMap();
        map.put("GAuthorization", "99c9934f049b4e78a290d60327a4d4d101");
        String s1 = OkHttp3Util.sendByPostJson("http://115.227.32.19:36680/v1/ss/gov/gw",
                s,
                map);
        JSONObject object1 = JSONObject.parseObject(s1);
        JSONArray jsonArray = object1.getJSONObject("data").getJSONArray("voList");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            System.out.println(jsonObject);

            JSONObject formDataJson = new JSONObject();
            formDataJson.put("textField_kq60qs6j", jsonObject.getString("orgName"));
            formDataJson.put("textField_kq60qs6k", jsonObject.getString("name"));

            formDataJson.put("textField_kq60qs6l", jsonObject.getString("typeNameCN"));

            formDataJson.put("textField_kq60qs6m", jsonObject.getString("remark"));

            String keyword = jsonObject.getString("keyword");
            if (!(Strings.isBlank(keyword) || keyword.equals("[]"))) {
                formDataJson.put("textField_kq60qs6n", keyword);
            }

            String welfare = jsonObject.getString("welfare");
            if (!(Strings.isBlank(welfare) || welfare.equals("[]"))) {
                formDataJson.put("textField_kq60qs6o", welfare);
            }

            Integer salaryRangeMin = jsonObject.getInteger("salaryRangeMin");
            if (salaryRangeMin != null && salaryRangeMin != -1) {
                Integer salaryRangeMax = jsonObject.getInteger("salaryRangeMax");
                formDataJson.put("textField_kq60qs6p", salaryRangeMin + "_" + salaryRangeMax);
            } else {
                formDataJson.put("textField_kq60qs6p", "不限");
            }

            formDataJson.put("textField_kq60qs6q", jsonObject.getInteger("recruitNum"));

            String educationRequirementMin = jsonObject.getString("educationRequirementMin");
            if (educationRequirementMin != null && !educationRequirementMin.equals("-1")) {
                formDataJson.put("textField_kq60qs6r", buildEducationCN(educationRequirementMin));
            } else {
                formDataJson.put("textField_kq60qs6r", "不限");
            }
            String experienceRequirement = jsonObject.getString("experienceRequirement");
            formDataJson.put("textField_kq60qs6s", buildExperienceCN(experienceRequirement));
            formDataJson.put("textField_kq60qs6t", jsonObject.getString("workAddress"));
            formDataJson.put("textField_kq60qs6u", jsonObject.getString("city"));
            formDataJson.put("textField_kq60qs6w", jsonObject.getString("contactNo"));

            String majorRequirementJoint = jsonObject.getString("majorRequirementJoint");
            if (!(Strings.isBlank(majorRequirementJoint) || "[]".equals(majorRequirementJoint))) {
                formDataJson.put("textField_kq60qs6x", majorRequirementJoint);
            }

            new ZzdServiceImpl().addPosition(formDataJson);
            System.out.println(formDataJson);

        }
        System.out.println();
    }


    private static String buildExperienceCN(String experienceRequirement) {
        if (Strings.isBlank(experienceRequirement)) {
            return "不限";
        }
        if (experienceRequirement.contains("∞")) {
            return "不限";
        }

        List<Integer> integers = JSONArray.parseArray(experienceRequirement, Integer.class);
        return integers.get(0) + " - " + integers.get(1) + "年";
    }


    private static String buildEducationCN(String educationRequirementMin) {
        if (educationRequirementMin.equals("0")) {
            return "初中";
        }
        if (educationRequirementMin.equals("1")) {
            return "高中";
        }
        if (educationRequirementMin.equals("2")) {
            return "中专";
        }
        if (educationRequirementMin.equals("3")) {
            return "大专";
        }
        if (educationRequirementMin.equals("4")) {
            return "本科";
        }
        if (educationRequirementMin.equals("5")) {
            return "研究生";
        }
        if (educationRequirementMin.equals("6")) {
            return "博士";
        }
        return "不限";
    }


    @Override
    public ZzdOrganizationDetailBO recursionGetOrgAndEmp(String orgCode) {
        if (StringUtils.isBlank(orgCode)) {
            return null;
        }
        ZzdOrganizationDetailBO organizationByCode = getOrganizationByCode(orgCode);
        if (organizationByCode != null) {
            List<String> empList = pageOrganizationEmployeeCodes(orgCode);
            if (CollectionUtils.isNotEmpty(empList)) {
                for (String emp : empList) {
                    ZzdEmployeeDetailBO employeeByCode = getEmployeeByCode(emp);
                    List<ZzdAccountBO> accountInfoByCode = getAccountInfoByCode(emp);
                    List<String> accountIds = accountInfoByCode.stream().map(s -> s.getAccountId().toString()).collect(Collectors.toList());
                    employeeByCode.setAccountId(String.join(",", accountIds));
                    List<ZzdPositionDetailBO> positions = listOrgEmployeePositionsByCodes(orgCode, emp);
                    if (CollectionUtils.isEmpty(positions)) {
                        continue;
                    }
                    employeeByCode.getPositions().addAll(positions);
                    organizationByCode.getEmployees().add(employeeByCode);
                }
            }

            List<String> list = pageSubOrganizationCodes(orgCode);
            if (CollectionUtils.isNotEmpty(list)) {
                for (String s : list) {
                    organizationByCode.getSubOrg().add(recursionGetOrgAndEmp(s));
                }
            }
        } else {
            return null;
        }

        return organizationByCode;
    }

    @Override
    public YiDaResponse queryVisitList(Integer pageNo, Integer pageSize) {
        log.info("获取走访信息,{},{}", pageNo, pageSize);
        String apiResult = queryYiDaResponse(YiDaFormIdConstant.VISIT, pageNo, pageSize);
        log.info("result:{}", apiResult);
        if (Strings.isBlank(apiResult)) {
            return null;
        }
        return JSON.parseObject(apiResult, YiDaResponse.class);
    }

    @Override
    public YiDaResponse queryStaffMemberInputList(Integer pageNo, Integer pageSize) {
        log.info("获取工作人员信息录入,{},{}", pageNo, pageSize);
        String apiResult = queryYiDaResponse(YiDaFormIdConstant.STAFF_MEMBER_INPUT, pageNo, pageSize);
        log.info("result:{}", apiResult);
        if (Strings.isBlank(apiResult)) {
            return null;
        }
        return JSON.parseObject(apiResult, YiDaResponse.class);
    }

    @Override
    public YiDaResponse queryPartyMemberList(Integer pageNo, Integer pageSize) {
        log.info("获取党员档案,{},{}", pageNo, pageSize);
        String apiResult = queryYiDaResponse(YiDaFormIdConstant.PARTY_MEMBER, pageNo, pageSize);
        log.info("result:{}", apiResult);
        if (Strings.isBlank(apiResult)) {
            return null;
        }
        return JSON.parseObject(apiResult, YiDaResponse.class);
    }

    @Override
    public YiDaResponse queryComeList(Integer pageNo, Integer pageSize) {
        log.info("获取来访来电,{},{}", pageNo, pageSize);
        String apiResult = queryYiDaResponse(YiDaFormIdConstant.COME, pageNo, pageSize);
        log.info("result:{}", apiResult);
        if (Strings.isBlank(apiResult)) {
            return null;
        }
        return JSON.parseObject(apiResult, YiDaResponse.class);
    }

    @Override
    public YiDaResponse queryEmploymentList(Integer pageNo, Integer pageSize) {
        log.info("获取就业创业,{},{}", pageNo, pageSize);
        String apiResult = queryYiDaResponse(YiDaFormIdConstant.EMPLOYMENT, pageNo, pageSize);
        log.info("result:{}", apiResult);
        if (Strings.isBlank(apiResult)) {
            return null;
        }
        return JSON.parseObject(apiResult, YiDaResponse.class);
    }

    @Override
    public YiDaResponse queryHelpList(Integer pageNo, Integer pageSize) {
        log.info("获取帮扶解困,{},{}", pageNo, pageSize);
        String apiResult = queryYiDaResponse(YiDaFormIdConstant.HELP, pageNo, pageSize);
        log.info("result:{}", apiResult);
        if (Strings.isBlank(apiResult)) {
            return null;
        }
        return JSON.parseObject(apiResult, YiDaResponse.class);
    }

    @Override
    public YiDaResponse queryActivityList(Integer pageNo, Integer pageSize) {
        log.info("获取主题活动,{},{}", pageNo, pageSize);
        String apiResult = queryYiDaResponse(YiDaFormIdConstant.ACTIVITY, pageNo, pageSize);
        log.info("result:{}", apiResult);
        if (Strings.isBlank(apiResult)) {
            return null;
        }
        return JSON.parseObject(apiResult, YiDaResponse.class);
    }

    @Override
    public YiDaResponse queryFwzStationList(Integer pageNo, Integer pageSize) {
        log.info("获取服务站点数据,{},{}", pageNo, pageSize);
        String apiResult = queryYiDaResponse(YiDaFormIdConstant.FWZ_STATION, pageNo, pageSize);
        log.info("result:{}", apiResult);
        if (Strings.isBlank(apiResult)) {
            return null;
        }
        return JSON.parseObject(apiResult, YiDaResponse.class);
    }


    public YiDaResponse queryNewUnemployment(Integer pageNo, Integer pageSize) {
        log.info("获取新版本就业创业,{},{}", pageNo, pageSize);
        String apiResult = queryYiDaResponse("FORM-GWLBV8TU25QIO4PI5XCL0ANQ3LR7Q1YS9HDKMKL4", pageNo, pageSize);
        log.info("result:{}", apiResult);
        if (Strings.isBlank(apiResult)) {
            return null;
        }
        return JSON.parseObject(apiResult, YiDaResponse.class);
    }

    @Override
    public String sendFwzMessage(List<String> userId, String title, String content, String idCardNo, String mobile, String realName, String address, String adminAreaValue) {
        log.info("发送服务站信息,{},{}", userId, title, content);
        String api = "/yida/process/startInstance.json";
        String formId = "FORM-GWLBV8TU25QIO4PI5XCL0ANQ3LR7Q1YS9HDKMKL4";
        String processCode = "TPROC--GWLBV8TU25QIO4PI5XCL0ANQ3LR7Q16W9HDKMKM4";

        JSONObject formDataJson = new JSONObject();
        formDataJson.put("employeeField_kmkdl5xv", userId);
        formDataJson.put("textField_kbq3fwt1", title);
        formDataJson.put("textareaField_kbkdvfo3", content);
        formDataJson.put("textField_kpxftctn", idCardNo);
        formDataJson.put("textField_kpxftctm", mobile);
        formDataJson.put("textField_kpxftctq", realName);
        formDataJson.put("textField_kpxnmxx8", address);
        formDataJson.put("textField_kss8yzpk", adminAreaValue);
        formDataJson.put("textField_krms7n4c", UUID.randomUUID().toString());
        formDataJson.put("numberField_kwkg2ta8", 1);

        ExecutableClient executableClient = getExecutableClient();
        PostClient postClient = executableClient.newPostClient(api);
        postClient.addParameter("formUuid", formId);
        postClient.addParameter("appType", appType);
        postClient.addParameter("systemToken", systemToken);
        postClient.addParameter("userId", pubUserId);
        postClient.addParameter("processCode", processCode);
        postClient.addParameter("formDataJson", formDataJson.toJSONString());
        String apiResult = postClient.post();

        log.info("result:{}", apiResult);
        if (Strings.isBlank(apiResult)) {
            return null;
        }

        return apiResult;
    }

    @Override
    public String sendFwzMessageOfXz(List<String> userId, List<String> shiId, String title, String content, String idCardNo, String mobile, String realName, String address, String adminAreaValue) {
        log.info("发送服务站信息,{},{}", userId, title, content);
        String api = "/yida/process/startInstance.json";
        String formId = "FORM-GWLBV8TU25QIO4PI5XCL0ANQ3LR7Q1YS9HDKMKL4";
        String processCode = "TPROC--GWLBV8TU25QIO4PI5XCL0ANQ3LR7Q16W9HDKMKM4";

        JSONObject formDataJson = new JSONObject();
        formDataJson.put("employeeField_kmkdl5xv", shiId);
        formDataJson.put("employeeField_kwkg2ta7", shiId);
        formDataJson.put("employeeField_kq0rb1kd", userId);
        formDataJson.put("textField_kbq3fwt1", title);
        formDataJson.put("textareaField_kbkdvfo3", content);
        formDataJson.put("textField_kpxftctn", idCardNo);
        formDataJson.put("textField_kpxftctm", mobile);
        formDataJson.put("textField_kpxftctq", realName);
        formDataJson.put("textField_kpxnmxx8", address);
        formDataJson.put("textField_kss8yzpk", adminAreaValue);
        formDataJson.put("textField_krms7n4c", UUID.randomUUID().toString());
        formDataJson.put("numberField_kwkg2ta8", 2);

        ExecutableClient executableClient = getExecutableClient();
        PostClient postClient = executableClient.newPostClient(api);
        postClient.addParameter("formUuid", formId);
        postClient.addParameter("appType", appType);
        postClient.addParameter("systemToken", systemToken);
        postClient.addParameter("userId", pubUserId);
        postClient.addParameter("processCode", processCode);
        postClient.addParameter("formDataJson", formDataJson.toJSONString());
        String apiResult = postClient.post();

        log.info("result:{}", apiResult);
        if (Strings.isBlank(apiResult)) {
            return null;
        }

        if (apiResult.contains("not authorized to")) {
            log.error("ak:{},sk{}, client:{}",  prodAk, prodSk, prodExecutableClient);
        }

        return apiResult;
    }

    public String sendFwzDifficultyMessage(List<String> userId, String id, String img, String realName, String idCardNo, String mobile, String soldierType,
                                           String genderStr, String birthday, String adminAreaValue, String address, String reason) {
        log.info("发送困难帮扶站信息,{},{}", userId);
        String api = "/yida/process/startInstance.json";
        String formId = "FORM-GWLBVQ3X27G1USM7S1VDTD7GYTJEB3IZIAQHUKP4";
        String processCode = "TPROC--GWLBVQ3X27G1USM7S1VDTD7GYTJEB3MZIAQHUKQ4";

        JSONObject formDataJson = new JSONObject();
        formDataJson.put("employeeField_kuhrnivc", userId);
        formDataJson.put("image_kuhrnium", img);
        formDataJson.put("numberField_kuhrniur", mobile);
        formDataJson.put("textField_kuhrniuq", idCardNo);
        formDataJson.put("textField_kpxftctm", mobile);
        formDataJson.put("textField_kuhrniup", realName);
        formDataJson.put("textField_kuhrniut", soldierType);
        formDataJson.put("textField_kuhrniuu", genderStr);
        formDataJson.put("textField_kuhrniuv", birthday);
        formDataJson.put("textField_kuhrniuw", adminAreaValue);
        formDataJson.put("textareaField_kuhrniuy", reason);
        formDataJson.put("textField_kuhrnive", id);

        formDataJson.put("textField_krms7n4c", UUID.randomUUID().toString());

        ExecutableClient executableClient = getExecutableClient();
        PostClient postClient = executableClient.newPostClient(api);
        postClient.addParameter("formUuid", formId);
        postClient.addParameter("appType", appType);
        postClient.addParameter("systemToken", systemToken);
        postClient.addParameter("userId", pubUserId);
        postClient.addParameter("processCode", processCode);
        postClient.addParameter("formDataJson", formDataJson.toJSONString());
        String apiResult = postClient.post();

        log.info("result:{}", apiResult);
        if (Strings.isBlank(apiResult)) {
            return null;
        }

        return apiResult;
    }

    private String queryYiDaResponse(String formId, Integer pageNo, Integer pageSize) {
        String api = "/yida/form/searchFormDatas.json";
        return queryYiDaBaseResponse(api, formId, pageNo, pageSize);
    }

    private String queryYiDaBaseResponse(String api, String formId, Integer pageNo, Integer pageSize) {
        ExecutableClient executableClient = getExecutableClient();
        PostClient postClient = executableClient.newPostClient(api);
        postClient.addParameter("formUuid", formId);
        postClient.addParameter("appType", appType);
        postClient.addParameter("systemToken", systemToken);
        postClient.addParameter("userId", pubUserId);
        postClient.addParameter("pageSize", String.valueOf(pageSize));
        postClient.addParameter("currentPage", String.valueOf(pageNo));

        return postClient.post();
    }


    public String addPosition(JSONObject formDataJson) {
        log.info("插入岗位信息,{},{}");
        String api = "/yida/form/saveFormData.json";
        String formId = "FORM-GWLBVEYY23G7RHHL43DR18BUK3OO022SBQ06QK1";

















        ExecutableClient executableClient = getExecutableClient();
        PostClient postClient = executableClient.newPostClient(api);
        postClient.addParameter("formUuid", formId);
        postClient.addParameter("appType", appType);
        postClient.addParameter("systemToken", systemToken);
        postClient.addParameter("userId", pubUserId);
        postClient.addParameter("formDataJson", formDataJson.toJSONString());
        String apiResult = postClient.post();

        log.info("result:{}", apiResult);
        if (Strings.isBlank(apiResult)) {
            return null;
        }

        return apiResult;
    }

    @Override
    public ZzdAccessTokenBO getAccessToken() {
        ExecutableClient executableClient = getExecutableClient();
        String api = "/gettoken.json";
        PostClient postClient = executableClient.newPostClient(api);
        postClient.addParameter("appkey", prodAk);
        postClient.addParameter("appsecret", prodSk);
        String apiResult = postClient.post();
        log.info("result:{}", apiResult);
        return extractObjectResult(apiResult, ZzdAccessTokenBO.class);
    }

    public ZzdAccessTokenBO getAccessToken_2() {
        ExecutableClient executableClient = getExecutableClient_2();
        String api = "/gettoken.json";
        PostClient postClient = executableClient.newPostClient(api);
        postClient.addParameter("appkey", prodAk_2);
        postClient.addParameter("appsecret", prodSk_2);
        String apiResult = postClient.post();
        log.info("result:{}", apiResult);
        return extractObjectResult(apiResult, ZzdAccessTokenBO.class);
    }

    @Override
    public ZzdUserInfoBO getUserInfoByAccessToken(String authCode) {
        ZzdAccessTokenBO accessToken = getAccessToken();
        BizCheckUtil.checkNotNull(accessToken, "获取浙政钉数据失败！");
        ExecutableClient executableClient = getExecutableClient();
        String api = "/rpc/oauth2/dingtalk_app_user.json";
        PostClient postClient = executableClient.newPostClient(api);
        postClient.addParameter("access_token", accessToken.getAccessToken());
        postClient.addParameter("auth_code", authCode);
        String apiResult = postClient.post();
        log.info("result:{}", apiResult);
        return extractObjectResult(apiResult, ZzdUserInfoBO.class);
    }

    @Override
    public ZzdUserInfoBO getUserInfoByAccessToken(String authCode,String source) {
        ZzdAccessTokenBO accessToken;
        ExecutableClient executableClient ;
        if ("V2".equals(source)) {
            accessToken = getAccessToken_2();
            BizCheckUtil.checkNotNull(accessToken, "获取浙政钉数据失败！");
            executableClient = getExecutableClient_2();
        } else {
            accessToken = getAccessToken();
            BizCheckUtil.checkNotNull(accessToken, "获取浙政钉数据失败！");
            executableClient = getExecutableClient();
        }
        String api = "/rpc/oauth2/dingtalk_app_user.json";
        PostClient postClient = executableClient.newPostClient(api);
        postClient.addParameter("access_token", accessToken.getAccessToken());
        postClient.addParameter("auth_code", authCode);
        String apiResult = postClient.post();
        log.info("result:{}", apiResult);
        return extractObjectResult(apiResult, ZzdUserInfoBO.class);
    }

    @Override
    public SzhzUserInfoBO getSzhzUserInfoByAccessToken(String accessToken) {
        log.info("获取数智杭州的用户信息,{}", accessToken);

        String url = "https://szhz.hangzhou.gov.cn:8027/szhz/system/getAccessTokenUser?accessToken=" + accessToken;
        String s = OkHttp3Util.sendByGetUrl(url);
        JSONObject object = JSONObject.parseObject(s);
        if (object.getInteger("code").equals(200)) {
            return object.getObject("data", SzhzUserInfoBO.class);
        }
        return null;
    }


    @Override
    public ZzdAccessTokenBO getJsApiAccessToken() {
        ZzdAccessTokenBO accessToken = getAccessToken();
        BizCheckUtil.checkNotNull(accessToken, "获取浙政钉数据失败！");

        ExecutableClient executableClient = getExecutableClient();
        String api = "/get_jsapi_token.json";
        PostClient postClient = executableClient.newPostClient(api);
        postClient.addParameter("accessToken", accessToken.getAccessToken());
        String apiResult = postClient.post();
        log.info("result:{}", apiResult);
        return extractObjectResult(apiResult, ZzdAccessTokenBO.class);
    }

    @Override
    public String sendFwzDifficultyCheckNotice(List<String> userId, String id, JSONArray img, String realName, String idCardNo, String mobile, String soldierType,
                                               String genderStr, String birthday, String adminAreaValue, String address, String reason) {
        log.info("发送困难帮扶站信息,{},{}", userId);
        String api = "/yida/process/startInstance.json";
        String formId = "FORM-GWLBV9FW2SK0UZ2WUXBPWFY6ZBT9M1QKMYPXUKDA";
        String processCode = "TPROC--GWLBV9FW2SK0UZ2WUXBPWFY6ZBT9M1TKMYPXUKEA";

        JSONObject formDataJson = new JSONObject();
        formDataJson.put("employeeField_kuz4gngv", userId);
        formDataJson.put("imageField_kunfnxft", img);
        formDataJson.put("textField_kuhrniuq", idCardNo);
        formDataJson.put("textField_kv21mdl5", mobile);
        formDataJson.put("textField_kuhrniup", realName);
        formDataJson.put("textField_kuhrniut", soldierType);
        formDataJson.put("textField_kuhrniuu", genderStr);
        formDataJson.put("textField_kuhrniuv", birthday);
        formDataJson.put("textField_kuhrniuw", adminAreaValue);
        formDataJson.put("textField_kuhrniux", address);
        formDataJson.put("textareaField_kuhrniuy", reason);
        formDataJson.put("textField_kuhrnive", id);

        ExecutableClient executableClient = getExecutableClient();
        PostClient postClient = executableClient.newPostClient(api);
        postClient.addParameter("formUuid", formId);
        postClient.addParameter("appType", appType);
        postClient.addParameter("systemToken", systemToken);
        postClient.addParameter("userId", pubUserId);
        postClient.addParameter("processCode", processCode);
        postClient.addParameter("formDataJson", formDataJson.toJSONString());
        String apiResult = postClient.post();

        log.info("result:{}", apiResult);
        if (Strings.isBlank(apiResult)) {
            return null;
        }

        return apiResult;
    }


    @Override
    public String sendFwzDifficultyMessage(List<String> userId, String id, String title, JSONArray img, String realName, String idCardNo, String mobile, String soldierType,
                                           String genderStr, String birthday, String adminAreaValue, String address, String reason) {
        log.info("发送困难帮扶站信息,{},{}", userId);
        String api = "/yida/process/startInstance.json";
        String formId = "FORM-GWLBV9FW2QM0UBPT4ZKW4F0J9CY182RYYWRXUKJG";
        String processCode = "TPROC--GWLBV9FW2QM0UBPT4ZKW4F0J9CY182UYYWRXUKKG";

        JSONObject formDataJson = new JSONObject();
        formDataJson.put("employeeField_kuhrnivc", userId);
        formDataJson.put("imageField_kunfnxft", img);
        formDataJson.put("textField_kw0f2pgc", title);
        formDataJson.put("textField_kad9pet8", idCardNo);
        formDataJson.put("textField_kaw7s75c", mobile);
        formDataJson.put("textField_kaw7s75d", realName);
        formDataJson.put("textField_kuhrniut", soldierType);
        formDataJson.put("textField_kaw7s75e", genderStr);
        formDataJson.put("textField_kuxry2n8", birthday);
        formDataJson.put("textField_kaw7s75b", adminAreaValue);
        formDataJson.put("numberField_kv0oxel3", 2);

        formDataJson.put("textareaField_kuhrniuy", reason);
        formDataJson.put("textField_kuhrnive", id);













        formDataJson.put("textField_krms7n4c", UUID.randomUUID().toString());

        ExecutableClient executableClient = getExecutableClient();
        PostClient postClient = executableClient.newPostClient(api);
        postClient.addParameter("formUuid", formId);
        postClient.addParameter("appType", appType);
        postClient.addParameter("systemToken", systemToken);
        postClient.addParameter("userId", pubUserId);
        postClient.addParameter("processCode", processCode);
        postClient.addParameter("formDataJson", formDataJson.toJSONString());
        String apiResult = postClient.post();

        log.info("result:{}", apiResult);
        if (Strings.isBlank(apiResult)) {
            return null;
        }

        return apiResult;
    }

    @Override
    public String sendFwzDifficultyMessageOfXz(List<String> userId, String uid, String title, JSONArray img, String realName, String idCardNo, String mobile, String soldierType, String genderStr, String birthday, String adminAreaValue, String address, String reason) {
        log.info("发送困难帮扶站信息,{},{}", userId);
        String api = "/yida/process/startInstance.json";
        String formId = "FORM-GWLBV9FW2QM0UBPT4ZKW4F0J9CY182RYYWRXUKJG";
        String processCode = "TPROC--GWLBV9FW2QM0UBPT4ZKW4F0J9CY182UYYWRXUKKG";

        JSONObject formDataJson = new JSONObject();
        formDataJson.put("employeeField_kuhrnivd", userId);
        formDataJson.put("imageField_kunfnxft", img);
        formDataJson.put("textField_kw0f2pgc", title);
        formDataJson.put("textField_kad9pet8", idCardNo);
        formDataJson.put("textField_kaw7s75c", mobile);
        formDataJson.put("textField_kaw7s75d", realName);
        formDataJson.put("textField_kuhrniut", soldierType);
        formDataJson.put("textField_kaw7s75e", genderStr);
        formDataJson.put("textField_kuxry2n8", birthday);
        formDataJson.put("textField_kaw7s75b", adminAreaValue);
        formDataJson.put("numberField_kv0oxel3", 3);
        formDataJson.put("textareaField_kuhrniuy", reason);
        formDataJson.put("textField_kuhrnive", uid);

        formDataJson.put("textField_krms7n4c", UUID.randomUUID().toString());

        ExecutableClient executableClient = getExecutableClient();
        PostClient postClient = executableClient.newPostClient(api);
        postClient.addParameter("formUuid", formId);
        postClient.addParameter("appType", appType);
        postClient.addParameter("systemToken", systemToken);
        postClient.addParameter("userId", pubUserId);
        postClient.addParameter("processCode", processCode);
        postClient.addParameter("formDataJson", formDataJson.toJSONString());
        String apiResult = postClient.post();

        log.info("result:{}", apiResult);
        if (Strings.isBlank(apiResult)) {
            return null;
        }

        return apiResult;
    }

    @Override
    public String sendHealthVisitMessage(List<String> userId, String uid, String title, String realName, String idCardNo, String mobile, String soldierType,
                                         String genderStr, String birthday, String adminAreaValue, String address, String reason, String deadline) {
        log.info("发送服务站信息,{},{}", userId, title);
        String api = "/yida/process/startInstance.json";
        String formId = "FORM-GWLBVZNT2DX5WLV662P82K9WTQ32U2EZEW76XKB8";
        String processCode = "TPROC--GWLBVZNT2DX5WLV662P82K9WTQ32U2GZEW76XKC8";

        JSONObject formDataJson = new JSONObject();
        formDataJson.put("employeeField_kx6819ui", userId);
        formDataJson.put("textField_kx6w33kq", uid);
        formDataJson.put("textareaField_kx6819ug", reason);
        formDataJson.put("textField_kx6819u6", idCardNo);
        formDataJson.put("textField_kx6819ue", deadline);
        formDataJson.put("textField_kx6819uq", mobile);
        formDataJson.put("textField_kx6819uc", realName);
        formDataJson.put("textField_kx8u2nnt", address);
        formDataJson.put("textField_kx8u2nnu", soldierType);
        formDataJson.put("textField_kx8u2nnv", genderStr);
        formDataJson.put("textField_kx8u2nnw", birthday);


        ExecutableClient executableClient = getExecutableClient();
        PostClient postClient = executableClient.newPostClient(api);
        postClient.addParameter("formUuid", formId);
        postClient.addParameter("appType", appType);
        postClient.addParameter("systemToken", systemToken);
        postClient.addParameter("userId", pubUserId);
        postClient.addParameter("processCode", processCode);
        postClient.addParameter("formDataJson", formDataJson.toJSONString());
        String apiResult = postClient.post();

        log.info("result:{}", apiResult);
        if (Strings.isBlank(apiResult)) {
            return null;
        }

        return apiResult;
    }

    @Override
    public String sendCommonVisitMessage(CommonVisitYidaRequest request) {
        log.info("发送标准服务站走访信息,{},{}", request);
        String api = "/yida/process/startInstance.json";
        String formId = "FORM-GWLBVZNT2DX5WLV662P82K9WTQ32U2EZEW76XKB8";
        String processCode = "TPROC--GWLBVZNT2DX5WLV662P82K9WTQ32U2GZEW76XKC8";

        JSONObject formDataJson = new JSONObject();
        formDataJson.put("employeeField_kx6819ui", request.getUserId());
        formDataJson.put("textField_kx6w33kq", request.getUid());
        formDataJson.put("textField_l27i4y6u", request.getTitle());
        formDataJson.put("textareaField_kx6819ug", request.getReason());
        formDataJson.put("textField_kx6819u6", request.getIdCardNo());
        formDataJson.put("textField_kx6819ue", request.getDeadline());
        formDataJson.put("textField_kx6819uq", request.getMobile());
        formDataJson.put("textField_kx6819uc", request.getRealName());
        formDataJson.put("textField_kx8u2nnt", request.getAddress());
        formDataJson.put("textField_kx8u2nnu", request.getSoldierType());
        formDataJson.put("textField_l27i4y6v", request.getTaskType());
        formDataJson.put("textField_kx8u2nnv", request.getGenderStr());
        formDataJson.put("textField_kx8u2nnw", request.getBirthday());
        formDataJson.put("textField_l3i74prd", request.getDealRemark());


        ExecutableClient executableClient = getExecutableClient();
        PostClient postClient = executableClient.newPostClient(api);
        postClient.addParameter("formUuid", formId);
        postClient.addParameter("appType", appType);
        postClient.addParameter("systemToken", systemToken);
        postClient.addParameter("userId", pubUserId);
        postClient.addParameter("processCode", processCode);
        postClient.addParameter("formDataJson", formDataJson.toJSONString());
        String apiResult = postClient.post();

        log.info("result:{}", apiResult);
        if (Strings.isBlank(apiResult)) {
            return null;
        }

        return apiResult;
    }


}
